package frame;

import bean.Tarefa;
import controle.CalcHora;
import dao.TarefaDAO;
import java.awt.Font;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class MainFrame extends javax.swing.JFrame {

    CalcHora calcHora = new CalcHora();
    List<Tarefa> lista;
    SimpleDateFormat hora = new SimpleDateFormat("HH:mm");
    SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
    DecimalFormat df = new DecimalFormat("R$ #,##0.00");//formato  
    RendimentosFrame rendimentosView = new RendimentosFrame();
    FeriadosFrame feriadosView = new FeriadosFrame();
    PrevisaoFrame previsaoView = new PrevisaoFrame();
    HelpFrame helpframe = new HelpFrame();
    Date data_jdate = null;
    String str_pesq, tipo_pesq = "normal";
    int selectedRow = 0;
            
 
    public MainFrame() {
        initComponents();
        jDateChooser_data.setDate(new java.util.Date());      
        alinhaCampos();
        preencher_jtable(tipo_pesq, str_pesq);
         }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu1 = new javax.swing.JMenu();
        jFormattedTextField_inicio = new javax.swing.JFormattedTextField();
        jFormattedTextField_fim = new javax.swing.JFormattedTextField();
        jFormattedTextField_duracao = new javax.swing.JFormattedTextField();
        jLabelduracao = new javax.swing.JLabel();
        jLabelinicio = new javax.swing.JLabel();
        jLabelfim = new javax.swing.JLabel();
        jLabeldata = new javax.swing.JLabel();
        jTextField_descricao = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButton_gravar = new javax.swing.JButton();
        jButton_limpar = new javax.swing.JButton();
        jButton_deletar = new javax.swing.JButton();
        jButton_pesquisar = new javax.swing.JButton();
        jDateChooser_data = new com.toedter.calendar.JDateChooser();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem_previsao = new javax.swing.JMenuItem();
        jMenuItem_feriados = new javax.swing.JMenuItem();
        jMenu_help = new javax.swing.JMenu();

        jMenu1.setText("jMenu1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Time Sheet PJ");
        setResizable(false);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });
        getContentPane().setLayout(null);

        jFormattedTextField_inicio.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        try {
            jFormattedTextField_inicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField_inicio.setAlignmentX(2.0F);
        jFormattedTextField_inicio.setAlignmentY(2.0F);
        jFormattedTextField_inicio.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField_inicioFocusLost(evt);
            }
        });
        getContentPane().add(jFormattedTextField_inicio);
        jFormattedTextField_inicio.setBounds(130, 60, 110, 18);

        jFormattedTextField_fim.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        try {
            jFormattedTextField_fim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField_fim.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField_fimFocusLost(evt);
            }
        });
        getContentPane().add(jFormattedTextField_fim);
        jFormattedTextField_fim.setBounds(250, 60, 110, 18);

        jFormattedTextField_duracao.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jFormattedTextField_duracao.setEditable(false);
        jFormattedTextField_duracao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT))));
        getContentPane().add(jFormattedTextField_duracao);
        jFormattedTextField_duracao.setBounds(370, 60, 110, 18);

        jLabelduracao.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabelduracao.setText("   DURAÇÃO");
        getContentPane().add(jLabelduracao);
        jLabelduracao.setBounds(390, 50, 80, 13);

        jLabelinicio.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabelinicio.setText("HORA INICIO");
        jLabelinicio.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabelinicioMouseClicked(evt);
            }
        });
        getContentPane().add(jLabelinicio);
        jLabelinicio.setBounds(150, 50, 80, 13);

        jLabelfim.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabelfim.setText("     HORA FIM");
        jLabelfim.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabelfimMouseClicked(evt);
            }
        });
        getContentPane().add(jLabelfim);
        jLabelfim.setBounds(260, 50, 80, 13);

        jLabeldata.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabeldata.setText("      DATA");
        jLabeldata.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabeldataMouseClicked(evt);
            }
        });
        getContentPane().add(jLabeldata);
        jLabeldata.setBounds(30, 50, 80, 13);

        jTextField_descricao.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jTextField_descricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_descricaoActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField_descricao);
        jTextField_descricao.setBounds(130, 90, 350, 18);

        jTextField2.setEditable(false);
        jTextField2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jTextField2.setText("       DESCRIÇÃO");
        jTextField2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jTextField2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField2MouseClicked(evt);
            }
        });
        getContentPane().add(jTextField2);
        jTextField2.setBounds(10, 90, 110, 17);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "id", "DATA", "DESCRICAO", "INICIO", "FIM", "DURAÇÃO"
            }
        ));
        jTable1.setGridColor(new java.awt.Color(255, 255, 255));
        jTable1.setShowHorizontalLines(false);
        jTable1.setShowVerticalLines(false);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 150, 470, 140);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("REGISTRO DE TAREFAS");
        jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel1);
        jLabel1.setBounds(50, 10, 380, 30);

        jPanel1.setLayout(new java.awt.GridLayout(1, 0));

        jButton_gravar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_gravar.setText("GRAVAR");
        jButton_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_gravarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_gravar);

        jButton_limpar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_limpar.setText("LIMPAR");
        jButton_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_limparActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_limpar);

        jButton_deletar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_deletar.setText("DELETAR");
        jButton_deletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_deletarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_deletar);

        jButton_pesquisar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_pesquisar.setText("PESQUISAR");
        jButton_pesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_pesquisarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_pesquisar);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 120, 470, 20);

        jDateChooser_data.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jDateChooser_data);
        jDateChooser_data.setBounds(10, 60, 110, 20);

        jMenu2.setText("PJ");

        jMenuItem1.setText("Rendimentos");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuItem_previsao.setText("Previsão");
        jMenuItem_previsao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_previsaoActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem_previsao);

        jMenuItem_feriados.setText("Feriados");
        jMenuItem_feriados.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_feriadosActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem_feriados);

        jMenuBar1.add(jMenu2);

        jMenu_help.setText("Help");
        jMenu_help.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu_helpMouseClicked(evt);
            }
        });
        jMenu_help.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu_helpActionPerformed(evt);
            }
        });
        jMenuBar1.add(jMenu_help);

        setJMenuBar(jMenuBar1);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-494)/2, (screenSize.height-350)/2, 494, 350);
    }// </editor-fold>//GEN-END:initComponents

    private void jLabeldataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabeldataMouseClicked

        if (jDateChooser_data.getDate() == null) {
            JOptionPane.showMessageDialog(null, "Selecione uma Data !");
        } else {
            preencher_jtable("data", data.format(jDateChooser_data.getDate()));
        }
        jFormattedTextField_inicio.setText("");
        jFormattedTextField_fim.setText("");
        jFormattedTextField_duracao.setText("");
        jTextField_descricao.setText("");

    }//GEN-LAST:event_jLabeldataMouseClicked

    private void jLabelinicioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelinicioMouseClicked

        jFormattedTextField_inicio.setText("" + hora.format(new java.util.Date()));

        if ( !jFormattedTextField_fim.getText().trim().equals("") ) {
            calcDuracao();
        } else {
            jFormattedTextField_duracao.setText("");
        }
    }//GEN-LAST:event_jLabelinicioMouseClicked

    private void jLabelfimMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelfimMouseClicked

        jFormattedTextField_fim.setText("" + hora.format(new java.util.Date()));

        if (!jFormattedTextField_inicio.getText().trim().equals("")) {
            calcDuracao();
        } else {
            jFormattedTextField_duracao.setText("");
        }
    }//GEN-LAST:event_jLabelfimMouseClicked

    private void jFormattedTextField_fimFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField_fimFocusLost
             
        if ( !jFormattedTextField_inicio.getText().trim().equals(":") && !jFormattedTextField_fim.getText().trim().equals(":")) {
            calcDuracao();
        } else {
            jFormattedTextField_duracao.setText("");
        }

    }//GEN-LAST:event_jFormattedTextField_fimFocusLost

    private void jButton_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_gravarActionPerformed

        TarefaDAO dao_save = new TarefaDAO();
        TarefaDAO dao_edit = new TarefaDAO();
        TarefaDAO dao_saveOrEdit = new TarefaDAO();
        Tarefa tarefa2 = new Tarefa();

        if (!jFormattedTextField_inicio.getText().trim().equals("") && !jFormattedTextField_fim.getText().trim().equals("")) {
            calcDuracao();
        } else {
            jFormattedTextField_duracao.setText("");
        }

        int linha = jTable1.getSelectedRow();

        if (jDateChooser_data.getDate() == null || jFormattedTextField_inicio.getText().trim().equals("") || jTextField_descricao.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Requisitos mínimos para gravação:\n data, hora inicio e descrição !");
        } else if (jDateChooser_data.getDate().after(new java.util.Date())) {
            JOptionPane.showMessageDialog(null, "Data mapior que a data atual !");
        } else if (jTextField_descricao.getText().length() > 255) {
            JOptionPane.showMessageDialog(null, "Tam max descrição = 255 !");
        } else if ( validaHora(jFormattedTextField_inicio.getText().trim()) ){ 
           JOptionPane.showMessageDialog(null, "Hora Inicial invalida !");
        } else if (  validaHora(jFormattedTextField_fim.getText().trim() ) ){ 
           JOptionPane.showMessageDialog(null, "Hora Final invalida !");
        }
        
        else if( duplicado() && linha >=0 )
        {
            JOptionPane.showMessageDialog(null, "Registro sem alterações !");
                                    
        }        
         else{
            
            if ( linha >=0 && jTable1.getValueAt(linha, 0)  != null ) 
                tarefa2.setId(new Integer(jTable1.getValueAt(linha, 0).toString().trim()));
            else
                tarefa2.setId(-1);
            
            if ( !jFormattedTextField_fim.getText().trim().equals("") ) 
                tarefa2.setHora_fim(jFormattedTextField_fim.getText().trim());
            
            if ( !jFormattedTextField_duracao.getText().trim().equals("") ) 
                tarefa2.setDuracao(jFormattedTextField_duracao.getText().trim());
            
            java.sql.Date data_t = new java.sql.Date(jDateChooser_data.getDate().getTime());  
            
            tarefa2.setData_tarefa( data_t );
            tarefa2.setDescricao(jTextField_descricao.getText().trim());
            tarefa2.setHora_inicio(jFormattedTextField_inicio.getText().trim());
            if ( !jFormattedTextField_duracao.getText().trim().equals("") ) 
            tarefa2.setMinutos(calcHora.diferencaMinutos(tarefa2.getHora_inicio(),tarefa2.getHora_fim()));
                                  
            String mensagem = "" ;
                            
            if ( tarefa2.getId() != -1 )
                mensagem = "Confirma a alteração do registro !";
            else
                mensagem = "Confirma a gravação do registro !";
            
            int opcao_editar = JOptionPane.showConfirmDialog(null, mensagem, "Confirmação", JOptionPane.YES_NO_OPTION);
            
            if ( tarefa2.getId() != -1 && opcao_editar == JOptionPane.YES_OPTION )
            {
                dao_edit.editar(tarefa2);
            }
            else if ( tarefa2.getId() == -1 && opcao_editar == JOptionPane.YES_OPTION ) 
            {
                dao_save.salvar(tarefa2);
            }
            
        jFormattedTextField_inicio.setText("");
        jFormattedTextField_fim.setText("");
        jFormattedTextField_duracao.setText("");
        jTextField_descricao.setText("");

                preencher_jtable(tipo_pesq, "");

        }
    }//GEN-LAST:event_jButton_gravarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        int linhasum = jTable1.getRowCount();
        int linha = jTable1.getSelectedRow();

        
        if (linhasum >= 1 && linha <= linhasum - 3) {

            try {
                jDateChooser_data.setDate(data.parse(jTable1.getValueAt(linha, 1).toString()));
                jTextField_descricao.setText(jTable1.getValueAt(linha, 2).toString());
                jFormattedTextField_inicio.setText(jTable1.getValueAt(linha, 3).toString());

                if (jTable1.getValueAt(linha, 4) != null) {
                    jFormattedTextField_fim.setText(jTable1.getValueAt(linha, 4).toString());
                }

                if (jTable1.getValueAt(linha, 5) != null) {
                    jFormattedTextField_duracao.setText(jTable1.getValueAt(linha, 5).toString());
                }

            } catch (ParseException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton_deletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_deletarActionPerformed

        int linha = jTable1.getSelectedRow();
        int linhasum = jTable1.getRowCount();

        TarefaDAO dao_del = new TarefaDAO();
        Tarefa tarefa_del = new Tarefa();

        if (linhasum > 2) {
            try {
                int id = new Integer(jTable1.getValueAt(linha, 0).toString());
                String excluir = "Confirma a exclusão do registro !";
                int opcao_escolhida = JOptionPane.showConfirmDialog(null, excluir, "exclusão", JOptionPane.YES_NO_OPTION);
                if (opcao_escolhida == JOptionPane.YES_OPTION) {
                    tarefa_del.setId(new Integer(id));
                    dao_del.deletar(tarefa_del);
                    preencher_jtable(tipo_pesq, str_pesq);
                }
                jDateChooser_data.setDate(new java.util.Date());
                jFormattedTextField_inicio.setText("");
                jFormattedTextField_fim.setText("");
                jFormattedTextField_duracao.setText("");
                jTextField_descricao.setText("");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Selecione um registro para excluir !");
            }
        }

    }//GEN-LAST:event_jButton_deletarActionPerformed

    private void jButton_pesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_pesquisarActionPerformed

        try
        {
            String pesq_desc = JOptionPane.showInputDialog(null, "Digite a descrição !");

            if ( pesq_desc != null )
            {
                preencher_jtable("descricao", pesq_desc);
                jDateChooser_data.setDate(new java.util.Date());
                jFormattedTextField_inicio.setText("");
                jFormattedTextField_fim.setText("");
                jFormattedTextField_duracao.setText("");
                jTextField_descricao.setText("");             
            }             
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Erro ao Pesquisar !" + e);   
        }

    }//GEN-LAST:event_jButton_pesquisarActionPerformed

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        alinhaCampos();
        
    }//GEN-LAST:event_formFocusGained

    private void jButton_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_limparActionPerformed

        jDateChooser_data.setDate(new java.util.Date());
        jFormattedTextField_inicio.setText("");
        jFormattedTextField_fim.setText("");
        jFormattedTextField_duracao.setText("");
        jTextField_descricao.setText("");
        preencher_jtable(tipo_pesq, str_pesq);
       
    }//GEN-LAST:event_jButton_limparActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

        if (!rendimentosView.isVisible()) {
            rendimentosView.setVisible(true);
        }

    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jTextField_descricaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_descricaoActionPerformed
        jButton_gravar.doClick();
    }//GEN-LAST:event_jTextField_descricaoActionPerformed

    private void jFormattedTextField_inicioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField_inicioFocusLost

        if ( !jFormattedTextField_inicio.getText().trim().equals(":")  && !jFormattedTextField_fim.getText().trim().equals(":") ) 
             calcDuracao();
        else  
            jFormattedTextField_duracao.setText("");
         
    }//GEN-LAST:event_jFormattedTextField_inicioFocusLost

    private void jMenu_helpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_helpActionPerformed
        if (!helpframe.isVisible()) {
            helpframe.setVisible(true);
        }
    }//GEN-LAST:event_jMenu_helpActionPerformed

    private void jMenu_helpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu_helpMouseClicked
        if (!helpframe.isVisible()) {
            helpframe.setVisible(true);
        }
    }//GEN-LAST:event_jMenu_helpMouseClicked

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
        
        selectedRow = jTable1.getSelectedRow(); 
        
        int count_linha = jTable1.getRowCount();
                        
        if ( count_linha > 2 && selectedRow > 0)
        {
        
        try
        {
            data_jdate = new java.sql.Date( data.parse( jTable1.getValueAt(selectedRow, 1).toString() ).getTime() );                
        }
        catch (ParseException ex)
        {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
     
            preencher_jtable("juntar", jTable1.getValueAt(selectedRow, 2).toString() );
            
            
         
        }
        
        
    }//GEN-LAST:event_jLabel1MouseClicked

    private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField2MouseClicked
        TarefaDAO t = new TarefaDAO();
        try {
            jTextField_descricao.setText(t.buscaUltimo());
        } catch (SQLException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }//GEN-LAST:event_jTextField2MouseClicked

    private void jMenuItem_previsaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_previsaoActionPerformed

    if (!previsaoView.isVisible()) {
            previsaoView.setVisible(true);
        }

    }//GEN-LAST:event_jMenuItem_previsaoActionPerformed

    private void jMenuItem_feriadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_feriadosActionPerformed
    if (!feriadosView.isVisible()) {
            feriadosView.setVisible(true);
        }
    }//GEN-LAST:event_jMenuItem_feriadosActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_deletar;
    private javax.swing.JButton jButton_gravar;
    private javax.swing.JButton jButton_limpar;
    private javax.swing.JButton jButton_pesquisar;
    private com.toedter.calendar.JDateChooser jDateChooser_data;
    private javax.swing.JFormattedTextField jFormattedTextField_duracao;
    private javax.swing.JFormattedTextField jFormattedTextField_fim;
    private javax.swing.JFormattedTextField jFormattedTextField_inicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabeldata;
    private javax.swing.JLabel jLabelduracao;
    private javax.swing.JLabel jLabelfim;
    private javax.swing.JLabel jLabelinicio;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem_feriados;
    private javax.swing.JMenuItem jMenuItem_previsao;
    private javax.swing.JMenu jMenu_help;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField_descricao;
    // End of variables declaration//GEN-END:variables

    private void preencher_jtable(String tipo, String texto) {

        TarefaDAO dao_lista = new TarefaDAO();
        Tarefa tarefa_list = new Tarefa();

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();
        centralizado.setHorizontalAlignment(SwingConstants.CENTER);

        JTableHeader titulos = jTable1.getTableHeader();

        titulos.setFont(new Font("Dialog", Font.BOLD, 10));

        jTable1.getColumnModel().getColumn(1).setCellRenderer(centralizado);
        jTable1.getColumnModel().getColumn(3).setCellRenderer(centralizado);
        jTable1.getColumnModel().getColumn(4).setCellRenderer(centralizado);
        jTable1.getColumnModel().getColumn(5).setCellRenderer(centralizado);

        jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(0).setMinWidth(0);
        jTable1.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);

        jTable1.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(60);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(20);

        try {
            
            if (tipo.equals("normal")) {
                lista = dao_lista.getLista();
            } else if (tipo.equals("descricao")) {
                lista = dao_lista.buscaDescricao(texto);
            } else if (tipo.equals("data")) {
                lista = dao_lista.buscaData(data.parse(texto));
            } else if (tipo.equals("juntar"))
            {   
                lista = dao_lista.juntarTarefas( texto ,data_jdate  );
            }
          int  tamanho_lista = lista.size();
            String dados = "";

           int minutos = 0;

            if (!lista.isEmpty()) {

                for (int i = 0; i < tamanho_lista; i++) {
                    tarefa_list = lista.get(i);

                    minutos = minutos + tarefa_list.getMinutos();

                    modelo.addRow(new Object[]{
                                tarefa_list.getId(),
                                data.format(tarefa_list.getData_tarefa()),
                                tarefa_list.getDescricao(),
                                tarefa_list.getHora_inicio(),
                                tarefa_list.getHora_fim(),
                                tarefa_list.getDuracao(),});

                }

                totalHoras(minutos);

            } else {

                modelo.addRow(new String[]{" ", ""});
                modelo.addRow(new String[]{" ", ""});

                int linha = jTable1.getRowCount();

                jTable1.setValueAt("Nenhum registro ", linha - 2, 2);
                jTable1.setValueAt("encontrado ! ", linha - 1, 2);

            }

        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "erro ao listar Jtable" + erro);
        }
    }

 
    public void alinhaCampos() {
                
        jFormattedTextField_inicio.setHorizontalAlignment(jFormattedTextField_inicio.CENTER);
        jFormattedTextField_fim.setHorizontalAlignment(jFormattedTextField_fim.CENTER);
        jFormattedTextField_duracao.setHorizontalAlignment(jFormattedTextField_duracao.CENTER);

    }

    public void calcDuracao() {
        try {
             
            String ret = calcHora.diferenca( jFormattedTextField_inicio.getText() ,jFormattedTextField_fim.getText() );

            if (ret.equals("erro")) {
                JOptionPane.showMessageDialog(null, "Hora inicial maior que hora final ! ");
                jFormattedTextField_fim.setText("");
            } else {
                jFormattedTextField_duracao.setText(ret);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void totalHoras(int min) {

        String totalformat = calcHora.minParaHora(min);
        totalformat = totalformat.replace(",", ":");

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.addRow(new String[]{" ", ""});
        modelo.addRow(new String[]{" ", ""});

        int linha = jTable1.getRowCount();

        jTable1.setValueAt("Total duraçâo ", linha - 1, 4);
        jTable1.setValueAt(totalformat, linha - 1, 5);

    }

    public boolean duplicado() {

        int linha = jTable1.getSelectedRow();

        boolean bdata = false, bhora_ini = false, bhora_fim = false,
                bduracao = false, bdescricao = false, result = false;
        
      String  data_tb  = "", hora_ini_tb  = "", hora_fim_tb  = "", duracao_tb  = "", descricao_tb  = "",
              data_txt = "", hora_ini_txt = "", hora_fim_txt = "", duracao_txt = "", descricao_txt = "";

        if (linha >=0 )
        {
        
           if( jTable1.getValueAt(linha, 1)!= null ) 
                data_tb = (String) jTable1.getValueAt(linha, 1);
           
           if( jTable1.getValueAt(linha, 3) != null )
                hora_ini_tb = (String) jTable1.getValueAt(linha, 3);
           
           if( jTable1.getValueAt(linha, 4) != null )
                hora_fim_tb = (String) jTable1.getValueAt(linha, 4);
           
           if( jTable1.getValueAt(linha, 5) != null )
                duracao_tb = (String) jTable1.getValueAt(linha, 5);
           
           if ( jTable1.getValueAt(linha, 2) != null )
                descricao_tb = (String) jTable1.getValueAt(linha, 2);
           
           if ( jDateChooser_data.getDate() != null )
                data_txt = data.format(jDateChooser_data.getDate());
           
           if ( !jFormattedTextField_inicio.getText().trim().equals("") )
                hora_ini_txt = jFormattedTextField_inicio.getText().trim();
           
           if ( !jFormattedTextField_fim.getText().trim().equals("") )
                hora_fim_txt = jFormattedTextField_fim.getText().trim();
           
           if ( !jFormattedTextField_duracao.getText().trim().equals("") )
                duracao_txt = jFormattedTextField_duracao.getText().trim();
           
           if ( !jTextField_descricao.getText().trim().equals("") )
                descricao_txt = jTextField_descricao.getText().trim();

        if (data_tb.equals(data_txt)) {
            bdata = true;
        }
        if (hora_ini_tb.equals(hora_ini_txt)) {
            bhora_ini = true;
        }
        if (hora_fim_tb.equals(hora_fim_txt)) {
            bhora_fim = true;
        }
        if (duracao_tb.equals(duracao_txt)) {
            bduracao = true;
        }
        if (descricao_tb.equals(descricao_txt)) {
            bdescricao = true;
        }
        if (bdata && bdescricao && bduracao && bhora_fim && bhora_ini) {
            result = true;
        }
                    
        }
        return result;
    }
    
    public boolean validaHora(String horatxt) {
        boolean erro = false;
        
        if (!horatxt.equals(":")) {

            int hora2 = Integer.parseInt(horatxt.substring(0, 2));
            int min = Integer.parseInt(horatxt.substring(3));

            if (hora2 > 24) {
                erro = true;
            } else if (min > 59) {
                erro = true;
            }
        }

        return erro;
    }

}
